package com.springboot.test.web.inter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.springboot.test.common.exception.BizException;
import com.springboot.test.common.enums.ErrorCode;
import com.springboot.test.common.enums.StaticKey;
import com.springboot.test.entity.UserEntity;
import com.springboot.test.service.RedisService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

import static com.springboot.test.common.enums.StaticKey.TOKEN_KEY;
import static com.springboot.test.common.enums.StaticKey.TOKEN_TIME;

/**
 * 自定义拦截器
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Resource
    private RedisService redisService;
    //拦截器拦截前的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //前端请求头携带token
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            throw new BizException(ErrorCode.USER_LOGIN);
        }
        if(token.equals(redisService.get(TOKEN_KEY+"admin"))){
            redisService.expireMin(TOKEN_KEY+"admin",token,TOKEN_TIME);
            return true;
        }
        //通过token获取用户信息
        UserEntity userInfo = redisService.getUserInfo(token);
        if(userInfo == null){
            throw new BizException(ErrorCode.USER_LOGIN);
//            return false;
        }
        //将用户信息放入请求头，可以在被拦截的任何方法中取得
        request.setAttribute(StaticKey.USER_INFO,userInfo);
        request.setAttribute(StaticKey.USER_CODE,userInfo.getUserId());
        request.setAttribute(StaticKey.USER_NAME,userInfo.getUserName());

        return true;
    }
}
